/**
 *
 */
package persistence;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author doralt
 *
 */
public class XMLFileHandler {

	/**
	 *
	 */
	public XMLFileHandler(){

	}

    /**
     * Load database.
     * @param file the file
     * @return the forum object created from database
     * @throws IOException Signals that an I/O exception has occurred.
     */
    public Object loadDB(File file) throws IOException{
        FileReader tFileReader = new FileReader(file);
        BufferedReader tBufReader = new BufferedReader(tFileReader);
        String tStr = "";
        while (tBufReader.ready()) {
            tStr += tBufReader.readLine();
        }
        Object tobj = XMLUtils.deserialize(tStr);
        return tobj;
    }

    /**
     * Save database.
     *
     * @param forum object need to be saved
     * @param file the file to save to
     *
     * @throws IOException Signals that an I/O exception has occurred.
     */
    public void saveDB(Object forum, File file) throws IOException {
        String tXmlStr = XMLUtils.serialize(forum);
        String filename = file.getCanonicalPath();
        this.writeToFile(tXmlStr, filename);
    }



    /**
     * Write to file.
     *
     * @param s the string we want to write to file
     * @param filename the filename
     * @throws IOException Signals that an I/O exception has occurred.
     */
    private void writeToFile(String s, String filename) throws IOException{
        // open file for output
        FileWriter tFileWriter = new FileWriter(filename);
        BufferedWriter tBufWriter = new BufferedWriter(tFileWriter);
        tBufWriter.write(s);
        // close the file
        tBufWriter.close();
    }

}
